<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>安全小卫士-笑笑门神</title>
  <link rel="stylesheet" href="/static/style.css" />
</head>
<body>
  <header>
    <h1>安全小卫士-笑笑门神 🐻</h1>
  </header>
  <main class="container">
    <section class="image-pane">
      <div class="image-container">
        {% if image_exists %}
          <img id="mainImage" src="{{ image_url }}" alt="image.jpg" />
        {% else %}
          <div class="placeholder">根目录未找到 image.jpg</div>
        {% endif %}
        <div class="info">
          <span>最后刷新：<span id="lastUpdated">从未</span></span>
        </div>
      </div>
      <div class="controls">
        <button id="refreshOnceBtn">手动刷新一次</button>
      </div>
    </section>
    <aside id="labelPane" class="label-pane">
      <h2>安全小卫士监控中</h2>
      <div id="labels">
        <div class="label-row"><span class="label-key"></span><span id="labelValue" class="label-badge">{{ label }}</span></div>
      </div>
      <div id="labelImage" class="label-image">
        <!-- 标签图片将在这里显示 -->
      </div>
      <div id="labelCaption" class="label-caption"></div>
    </aside>
  <!-- 陌生人弹窗 -->
  <div id="strangerModal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
    <div class="modal-content">
      <div class="modal-header">
        <h3 id="modalTitle">注意安全！🚨</h3>
      </div>
      <div class="modal-body">
        <img src="/static/wolf.svg" alt="大灰狼" class="modal-figure" />
        <p class="modal-text">检测到陌生人～请和老师或家人在一起！</p>
      </div>
      <div class="modal-actions">
        <button id="modalCloseBtn" class="modal-close-btn">我知道了</button>
      </div>
    </div>
  </div>

  </main>
  <footer>
    <small>作者：顾慕言、顾闻、王韵</small>
  </footer>

  <script>
    let imgEl = document.getElementById('mainImage');
    const lastUpdatedEl = document.getElementById('lastUpdated');
    const labelEl = document.getElementById('labelValue');
    const refreshOnceBtn = document.getElementById('refreshOnceBtn');
    let refreshTimer = null;
    let isRefreshing = false;

    async function refresh() {
      try {
        if (isRefreshing) return;
        isRefreshing = true;
        // 先刷新图片
        const resp = await fetch('/api/refresh_image');
        const data = await resp.json();
        // 如果首次没有图片标签，但刷新返回了图片地址，则动态创建图片元素
        if (data.image_url) {
          const existing = document.getElementById('mainImage');
          if (existing) {
            existing.src = data.image_url;
            imgEl = existing;
          } else {
            const container = document.querySelector('.image-container');
            if (container) {
              const newImg = document.createElement('img');
              newImg.id = 'mainImage';
              newImg.alt = 'image.jpg';
              newImg.src = data.image_url;
              const placeholder = container.querySelector('.placeholder');
              if (placeholder) {
                container.insertBefore(newImg, placeholder);
                placeholder.remove();
              } else {
                const infoEl = container.querySelector('.info');
                if (infoEl) container.insertBefore(newImg, infoEl);
                else container.appendChild(newImg);
              }
              imgEl = newImg;
            }
          }
        }
        if (lastUpdatedEl) {
          const dt = new Date((data.timestamp || Date.now()) * 1000);
          lastUpdatedEl.textContent = dt.toLocaleString();
        }
        // 刷新图片后再获取标签
        if (labelEl) {
          labelEl.textContent = '获取中…';
        }
        const labelResp = await fetch('/api/get_label');
        const labelData = await labelResp.json();
        if (labelEl) {
          const rawLabel = (labelData.label || '').trim();
          const label = rawLabel.length ? rawLabel : '获取中...';
          // 可爱展示文案（不影响原标签变量）
          let displayLabel = label;
          if (rawLabel === 'stranger' || rawLabel === '陌生人') displayLabel = '陌生人 🚨';
          else if (rawLabel === 'family' || rawLabel === '熟人') displayLabel = '熟人 😊';
          else if (rawLabel === '没有人') displayLabel = '没有人';
          else if (!rawLabel) displayLabel = '获取中...';
          labelEl.textContent = displayLabel;
 
          const labelPaneEl = document.getElementById('labelPane');
          if (labelPaneEl) {
            labelPaneEl.classList.remove('status-stranger', 'status-family');
          }
          labelEl.classList.remove('badge-stranger', 'badge-family');
          
          // 根据标签显示不同图片并应用状态样式 + 弹窗控制
          const labelImageEl = document.getElementById('labelImage');
          const modal = document.getElementById('strangerModal');
          const closeBtn = document.getElementById('modalCloseBtn');
          if (closeBtn && modal) {
            closeBtn.onclick = () => modal.classList.add('hidden');
          }
          if (labelImageEl) {
            if (rawLabel === 'stranger' || rawLabel === '陌生人') {
              labelImageEl.innerHTML = '<img src="/static/wolf.svg" alt="大灰狼" class="label-character-image">';
              if (labelPaneEl) labelPaneEl.classList.add('status-stranger');
              labelEl.classList.add('badge-stranger');
              const capEl = document.getElementById('labelCaption');
              if (capEl) capEl.textContent = '小心陌生人哦～请和老师、爸爸妈妈在一起！';
              // // 显示弹窗
              // if (modal) modal.classList.remove('hidden');
              // 获取标签成功后再触发报警
              try {
                await fetch('/api/alarm', { method: 'POST' });
              } catch (err) {
                console.error('报警触发失败', err);
              }
            } else if (rawLabel === 'family' || rawLabel === '熟人') {
              labelImageEl.innerHTML = '<img src="/static/grandpa.svg" alt="老爷爷" class="label-character-image">';
              if (labelPaneEl) labelPaneEl.classList.add('status-family');
              labelEl.classList.add('badge-family');
              const capEl = document.getElementById('labelCaption');
              if (capEl) capEl.textContent = '欢迎回家～和家人一起最安全！';
              if (modal) modal.classList.add('hidden');
            } else {
              labelImageEl.innerHTML = ''; // 清空图片
              const capEl = document.getElementById('labelCaption');
              if (capEl) capEl.textContent = ''; 
              if (modal) modal.classList.add('hidden');
            }
          }
          // 定时刷新由全局计时器控制（每5秒一次）
          isRefreshing = false;
        }
      } catch (e) {
        console.error('刷新失败', e);
        if (labelEl) labelEl.textContent = '获取失败';
        isRefreshing = false;
      }
    }

    // 已取消固定间隔刷新

    refreshOnceBtn.addEventListener('click', () => {
      refresh();
    });

    // 固定间隔已移除，无需处理间隔选择

    // 初次加载立即刷新一次，并开启每5秒定时刷新
    refresh();
    refreshTimer = setInterval(refresh, 5000);
  </script>
</body>
</html>